package com.lcy.redis.redistest;

import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

/**
 * 不要使用这个类，这是jedis时遗留下来的方法，redisson不是很适用
 *
 * @author player six
 * @email jslcylcy@163.com
 * @create 2018-05-21 15:21
 **/
@Component
public class RedisUtil {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * redis设置键值对
     *
     * @param key
     * @param value
     * @return
     */
    public String set(String key, String value) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        return bucket.getAndSet(value);
    }

    /**
     * redis获取值
     *
     * @param key
     * @return
     */
    public String get(String key) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    /**
     * redis获取锁
     *
     * @param lock
     * @return
     */
    public RLock tryLock(String lock) {
        return redissonClient.getLock(lock);
    }

    /**
     * redis删除锁
     *
     * @param lock
     * @return
     */
    public void unLock(String lock) {
        RLock rLock = redissonClient.getLock(lock);
        rLock.unlock();
    }

    /**
     * 获取写锁
     *
     * @param lock
     * @return
     */
    public Lock tryWriteLock(String lock) {
        ReadWriteLock rLock = redissonClient.getReadWriteLock(lock);
        return rLock.writeLock();
    }

    /**
     * 尝试读锁
     *
     * @param lock
     * @return
     */
    public Lock tryReadLock(String lock) {
        ReadWriteLock rLock = redissonClient.getReadWriteLock(lock);
        return rLock.readLock();
    }

}
